﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LDSP.BRL;
using LDSP.Util;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using BYFW.SFL;
using System.Configuration;
using ImplementationInitialization.Constants;

namespace ImplementationInitialization
{
    public class FinalImport
    {
        protected IDictionary<string, Catalog> _catalogDic = BaseDataInitial.GetCatalogs();
        protected IDictionary<string, Category> _categoryDic = BaseDataInitial.GetCategories();
        protected IList<Codification> _newCodifications = new List<Codification>();
        protected IList<ExposureDraft> _newExposureDrafts = new List<ExposureDraft>();
        protected IDictionary<Codification, string> _invalidList = new Dictionary<Codification, string>();

        public ImportCodificationResult ImportResult { get; set; }
        public DateTime UploadDT { get; set; }

        protected bool _isForceImport = false;

        public void Run(string filename)
        {
            string forceImport = ConfigurationManager.AppSettings["AttachmentForceImport"];
            if (!string.IsNullOrEmpty(forceImport))
            {
                _isForceImport = bool.Parse(forceImport);
            }

            ExcelClass cls = new ExcelClass(filename);

            Logger.WriteLog("Begin File Import : " + filename);

            try
            {
                for (int i = 0; i < cls.Sheets.Count; i++)
                {
                    DataTable dt = cls.ToDataTable(i);
                    string sheetName = cls.Sheets[i].Name;

                    Logger.WriteLog("Begin Excel Sheet : " + sheetName);

                    ImportSheet(filename, dt, sheetName);

                    Logger.WriteLog("End Excel Sheet : " + sheetName);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog("Exception : " + ex.Message);
            }

            Logger.WriteLog("End File Import : " + filename);
        }

        protected virtual void ImportSheet(string filename, DataTable dt, string sheetName)
        {
            if (!string.IsNullOrEmpty(sheetName) && _catalogDic.ContainsKey(sheetName))
            {
                int catalogID = _catalogDic[sheetName].ID;
                Import(filename, dt, catalogID, sheetName);
            }
            else
            {
                WriteImportItemResult(string.Empty, filename, sheetName, "Sheet名不是系统里存在的栏目", false);
            }
        }

        public void RefreshDisableList()
        {
            foreach (Codification cod in _invalidList.Keys)
            {
                try
                {
                    CreateDisableRelationship(cod);
                }
                catch (Exception ex)
                {
                    Logger.WriteLog("Exception Creating Invalid list for Codification : " + cod.Name);
                }
            }
        }

        public int GetInt(object origin)
        {
            if (origin == null)
            {
                return 0;
            }
            return CommonOP.GetInt(origin.ToString(), false);
        }

        public void UpdateAttachment(string fileDir, string siteDir)
        {
            if (Directory.Exists(fileDir) && Directory.Exists(siteDir))
            {
                UpdateAttachement(fileDir, siteDir, siteDir);
            }
        }

        protected virtual IList<string> GetDisableList(Codification cod)
        {
            return null;
        }

        protected virtual void Import(string filename, DataTable dt, int catalogID, string sheetName) { }

        protected virtual string AnalyseCodName(string fileName)
        {
            string codName = fileName.LastIndexOf(".") > -1 ? fileName.Substring(0, fileName.LastIndexOf(".")) : fileName;
            if (Regex.IsMatch(codName, "_.*_"))
            {
                Match m = Regex.Match(codName, "_.*_");
                codName = m.Value.Remove(0, 1);//Remove the first _.
                codName = codName.Remove(codName.Length - 1, 1);//Remove the last _.
                codName = codName.Trim();
            }

            return codName;
        }

        protected virtual void WriteImportAttachmentResult(string fileName, string message, bool success) { }

        protected virtual void WriteImportItemResult(string codName, string excel, string sheet, string message, bool success) { }

        protected void CreateDisableRelationship(Codification cod)
        {
            IList<string> list = new List<string>();
            if (_invalidList.ContainsKey(cod) && !string.IsNullOrEmpty(_invalidList[cod]))
            {
                list = GetDisableList(cod);
            }

            IDictionary<string, Codification> existed = BaseDataInitial.GetExistedCodification();
            for (int i = 0; i < list.Count; i++)
            {
                int id = existed.ContainsKey(list[i]) ? existed[list[i]].ID : -1;
                if (id > 0)
                {
                    R_DisableDoc ett = new R_DisableDoc();
                    ett.SourceID = cod.ID;
                    ett.DestinationID = id;
                    if (ett.Destination.DocType != cod.DocType
                        || ett.Destination.EnterpriseID != cod.EnterpriseID
                        || ett.SourceID == ett.DestinationID)
                    {
                        continue;
                    }
                    ett.Add();
                }
            }
        }

        /// <summary>
        /// 截取法规标准名字符串里的中文名。
        /// 去掉了原始法规标准名前后的空格，以及可能有的"\n"和"/"及后面的英文部分，最后再把得到的字符前后的空格去掉。
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected string GetChineseName(string name)
        {
            name = name.Trim();

            //截取中文名。
            if (name.Contains(SpecialMark.SPLITTER_ENTER))
            {
                name = name.Substring(0, name.IndexOf(SpecialMark.SPLITTER_ENTER)).Trim();
            }
            else if (name.Contains(SpecialMark.SPLITTER_BLANK))
            {
                name = name.Substring(0, name.IndexOf(SpecialMark.SPLITTER_BLANK)).Trim();
            }

            return name.Trim();
        }

        protected virtual void UpdateAttachement(string sourceDir, string desDir, string root)
        {
            IDictionary<string, Codification> codDic = BaseDataInitial.GetExistedCodification();
            foreach (string filePath in Directory.GetFiles(sourceDir))
            {
                string fileName = Path.GetFileName(filePath);
                string codName = AnalyseCodName(fileName);

                try
                {
                    if (codDic.ContainsKey(codName))
                    {
                        if (string.IsNullOrEmpty(codDic[codName].FileExtension) || _isForceImport)
                        {
                            codDic[codName].CreateNewFile(fileName);
                            codDic[codName].Update();

                            File.Copy(sourceDir + "\\" + fileName, desDir + "\\" + codDic[codName].FileExtension, true);

                            WriteImportAttachmentResult(fileName, "", true);
                        }
                        else
                        {
                            WriteImportAttachmentResult(fileName, "对应法规的附件已添加", false);
                        }

                    }
                    else
                    {
                        WriteImportAttachmentResult(fileName, "系统里没有对应的法规", false);
                    }
                }
                catch (Exception ex)
                {
                    string message = "Error update attachment for Codification : " + codName + " File : " + fileName + " Exception : " + ex.Message;
                    Logger.WriteLog(message);
                    WriteImportAttachmentResult(fileName, message, false);
                }
            }

            foreach (string dir in Directory.GetDirectories(sourceDir))
            {
                string desdir = desDir + "\\" + Path.GetFileName(dir);
                Directory.CreateDirectory(desdir);

                UpdateAttachement(dir, desdir, root);
            }
        }

        private void CopyFilesDirs(string sourceDir, string desDir)
        {
            string[] arrDirs = Directory.GetDirectories(sourceDir);
            string[] arrFiles = Directory.GetFiles(sourceDir);
            if (arrFiles.Length != 0)
            {
                for (int i = 0; i < arrFiles.Length; i++)
                    File.Copy(sourceDir + "\\ " + Path.GetFileName(arrFiles[i]), desDir + "\\ " + Path.GetFileName(arrFiles[i]), true);
            }

            if (arrDirs.Length != 0)
            {
                for (int i = 0; i < arrDirs.Length; i++)
                {
                    Directory.CreateDirectory(desDir + "\\ " + Path.GetFileName(arrDirs[i]));
                    CopyFilesDirs(sourceDir + "\\ " + Path.GetFileName(arrDirs[i]), desDir);//递归调用 
                }
            }
            else
                return;
        }
    }
}
